<template>
	<div>
		<!--1.连接信息  -->
		<van-row>
			<van-col span="20">
				<van-field v-model="room" placeholder="请输入房间号" ></van-field>
				<van-field v-model="name" placeholder="请输入昵称" ></van-field>
				<van-button @click="connect()" >加入聊天室</van-button>
				<van-button @click="exit()" >退出聊天室</van-button>
			</van-col>
		</van-row>
		
		<!-- 2.发送区 -->
		<van-row offset="2">
			<van-col>
				<van-field v-model="msg" placeholder="请输入聊天信息"></van-field>
				<van-button @click="sendMsg()" >发送信息</van-button>
			</van-col>
			
		</van-row>
		
		<!-- 3.聊天区 -->
		
		<div v-for="m in msglist">
			<val-row v-if="m.type==1" :key="m">
				<!-- 别人的消息 -->
				<van-col span="4" >
						<van-image
						  round
						  width="2rem"
						  height="2rem"
						  src="https://img.yzcdn.cn/vant/cat.jpeg"
						/>
				</van-col>
				<van-col span="2">他人</van-col>
				<van-col span="18">{{m.msg}}</van-col>
			</val-row>
			
			<val-row v-if="m.type==2">
				<van-col span="18" style="margin-right: 60px;">{{m.msg}}</van-col>
				<van-col span="2">{{name}}</van-col>
				<!-- 别人的消息 -->
				<van-col span="4">
						<van-image  round
						width="2rem"
						height="rem"
						src="https://img.yzcdn.cn/vant/cat.jpeg"></van-image>
				</van-col>
			</val-row>
			
			
			<val-row v-if="m.type==3">
				<!-- 系统消息 -->
				<van-col span="8"></van-col>
				<van-col span="8" style="font-size: 0.75rem;">{{m.msg}}</van-col>
				
				<van-col span="8"></van-col>
			</val-row>
			
			
			
		</div>
	</div>
</template>

<script>
	var ws;
	
	export default{
		data(){
			return{
				id:1,
				name:"",
				room:"",
				msg:"",
				msglist:[
					{
					id:1,
					type:1,
					msg:"",
					},
				]
			}
		},
		mounted(){
			
		},
		methods:{
			connect(){
				if(this.room.length>0 && this.name.length>0){
					ws=new WebSocket("ws://10.8.154.50:8080/chat/server/"+this.room+"/"+this.name);
					var that = this;
					ws.onmessage=function(evt){
						that.id++;
						that.msglist.push({
							id:that.id,
							type:1,
							msg:evt.data,
						})
						if(that.id%10==0){
							that.id++;
							that.msglist.push({
								id:that.id,
								type:3,
								msg:new Date().toLocaleString(),
							})
							
						}
						
					}
					
				}else{
					alert("亲，请输入连接信息");
				}
				
			},
			//发送消息
			sendMsg(){
				this.id++;
				ws.send(this.msg);
				this.msglist.push({
					id:this.id,
					type:2,
					msg:this.msg,
				})
				
			},//接受消息
			receiveMsg(evt){
				this.id++;
				this.msglist.push({
					id:this.id,
					type:1,
					msg:evt.data
				});
				if(id%10==0){
					this.id++;
					this.msglist.push({
						id:this.id,
						type:3,
						msg:new Date().toLocaleTimeString()
					});
				}
				
			},
			exit(){
				this.ws.close();
			}
			
		}
	}
</script>

<style>
</style>
